﻿
<link href='https://fullcalendar.io/assets/demo-to-codepen.css' rel='stylesheet' />
<link href='https://unpkg.com/@fullcalendar/core@4.3.1/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/@fullcalendar/timeline@4.3.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/@fullcalendar/resource-timeline@4.3.0/main.min.css' rel='stylesheet' />


<script src='https://fullcalendar.io/assets/demo-to-codepen.js'></script>
<script src='https://unpkg.com/@fullcalendar/core@4.3.1/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/interaction@4.3.0/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/timeline@4.3.0/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/resource-common@4.3.1/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/resource-timeline@4.3.0/main.min.js'></script>
<!--Moment.js-->
<script src="https://cdn.bootcss.com/moment.js/2.24.0/moment.js"></script>

<style>
    .fc-widget-content {
        height: 60px;
    }

    .fc-body .fc-resource-area .fc-cell-content {
        padding-top: 8px;
        padding-bottom: 8px;
        text-align: center;
        width: 120px;
    }

    html, body {
        margin: 0;
        padding: 0;
        font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
        font-size: 14px;
    }

    #calendar {
        max-width: 900px;
        margin: 0px auto;
        background-color: #fff;
        padding: 10px;
    }


    .fc-button-primary:not(:disabled).fc-button-active, .fc-button-primary:not(:disabled):active {
        color: #8d5502;
        background-color: #FFEB3B;
        border-color: #dc9110;
    }

    .fc-button-primary {
        color: #fff;
        background-color: #FF9800;
        border-color: #FF5722;
    }

        .fc-button-primary:hover {
            color: #8d5502;
            background-color: #FFEB3B;
            border-color: #dc9110;
        }
        .fc-button-primary:disabled {
    color: #000;
    background-color: #c3c6c8;
    border-color: #ababac;
}

        .fc-timeline-event .fc-title-wrap {
    flex-grow: 1;
    min-width: 0;
    cursor: pointer;
}

        .fc-timeline .fc-cell-text {
    display: inline-block;
    padding-left: 4px;
    padding-right: 4px;
    color: #575757;
}

        .hearderSearch
    {
        padding-top: 10px;
    border-bottom: 1px solid #d3d1d1;
    padding-bottom: 5px;
    background-color: #fff;
    }
        .fixDivBg{
                position: fixed;
    z-index: 100;
    background-color:#929292c4;
    width: 100%;
    height: 100%;
    display:none;
        }

        .fixDivContent{
                position: fixed;
    z-index: 101;
    right:0px;
    background-color:#fff;
    width: 80%;
    height: 100%;
    display:none;
        }
</style>
<div>
    <div class="fixDivBg">

    </div>
    <div class="fixDivContent">

    </div>
</div>
<div class="hearderSearch">
    <div class="container-fluid" id="SearchHeader">
        <div class="row">
            <div class="col-lg-2 col-md-3 col-sm-12">
               <a class="btn btn-danger" target="_blank" href="https://appcnhkdm450.digitalmaker.asia.pwcinternal.com/pwccnhk/gtsventure/vForm/ResourceBooking/Add/">Book new resource</a>
            </div>
            <div class="col-lg-3 col-md-4 col-sm-12">
                <select id="project" class="form-control">
                    <option value="">All Projects</option>
                </select>
            </div>
            <div class="col-lg-3 col-md-4 col-sm-12">
                <select id="Team" class="form-control">
                    <option value="">All Teams</option>
                </select>
            </div>
        </div>
    </div>
</div>

<div id='calendar'></div>
<script>
    var ProjectList = [];
    var TeamList = [];
    var ResourceList = [];
    var calendar;
    var IconUrl = "http://hkapppwv918/ImageWebApi/api/Image/{{StaffCode}}?type=1";
    var requrl = "/pwccnhk/gtsventure/customapi/RetrieveQueryDocs";
</script>

<script>
    
    function GetProjectList() {

        var Jsondata = {};
        Jsondata.SearchItem = [];
        Jsondata.EntityName = "7m2ncu0h5i";
        Jsondata.index = 0;
        Jsondata.size = 100;
        Jsondata.Columns = ["_id", "ProjectNameNew"];
        Jsondata.SearchItem.push({ "Name": "IsDeleted", "Value": 0, "Operator": 'Equal', 'Method': 'AND' });
        Jsondata.Order = {
            "ProjectNameNew": "Ascending"
        };
        $.ajax({
            url: requrl,
            type: 'POST',
            data: Jsondata,
            async: true,
            success: function (response) {
                if (response.StatusCode === 200) {
                    if (response.Data.total > 0) {
                        $.each(response.Data.rows, function (index, item) {
                            var obj = {
                                projectCode: item._id
                                , ProjectName: item.ProjectNameNew
                            };
                            ProjectList.push(obj);
                            $("#project").append("<option value='" + item._id + "'>" + item.ProjectNameNew + "</option>");
                        
                        });
                        console.log("GetProjectList", ProjectList);
                      

                        $("#project").bind("change", function () {
                            calendar.destroy();
                            LoadCalendar();
                        });
                    }
                }
                return [];
            }
        });
        return ProjectList;
    };

    function GetTeams() {
        var Jsondata = {};
        Jsondata.SearchItem = [];
        Jsondata.EntityName = "8gtrb625m0h";
        Jsondata.index = 0;
        Jsondata.size = 100;
        Jsondata.Columns = ["_id", "TeamName", "Metadata-TeamMembers_relationsvalue", "TeamMembers"];
        Jsondata.SearchItem.push({ "Name": "IsDeleted", "Value": 0, "Operator": 'Equal', 'Method': 'AND' });
        Jsondata.Order = {
            "TeamName": "Ascending"
        };
        $.ajax({
            url: requrl,
            type: 'POST',
            data: Jsondata,
            async: true,
            success: function (response) {
                if (response.StatusCode === 200) {
                    if (response.Data.total > 0) {
                        $.each(response.Data.rows, function (index, item) {
                            var obj = {
                                TeamCode: item._id
                                , TeamName: item.TeamName
                                , TeamMenberOjbects: item["Metadata-TeamMembers_relationsvalue"]
                                , TeamMembers: item.TeamMembers
                            };
                            TeamList.push(obj);
                            $("#Team").append("<option value='" + item._id + "'>" + item.TeamName + "</option>");
                        });
                        console.log("GetTeams", TeamList);
                        $("#Team").bind("change", function () {
                            calendar.destroy();
                            LoadCalendar();
                        });

                        LoadCalendar();
                    }
                }
                return [];
            }
        });
        return TeamList;
    };

    function GetResources(callback) {
        ResourceList = [];
        var teamcode = $("#Team").val();
        $.each(TeamList, function (i, o) {
            if (teamcode == "" || o.TeamCode == teamcode) {
                $.each(o.TeamMenberOjbects, function (j, k) {
                    ResourceList.push({
                        "id": k.StaffId,
                        "title": k.StaffName,
                        "eventColor": "orange"
                    });
                });
            };
        });
        console.log("GetResources", ResourceList);
        callback(ResourceList);
    };
    
    function GetTeamStaff() {
        var Members = [];
        var teamcode = $("#Team").val();
        $.each(TeamList, function (i, o) {
            if (teamcode == "" || o.TeamCode == teamcode) {
                $.each(o.TeamMenberOjbects, function (j, k) {
                    Members.push({
                        "id": k.StaffId,
                        "title": k.StaffName,
                        "eventColor": "orange"
                    });
                });
            };
        });
        console.log("Members", Members);
        return Members;
    };

    function GetEvents(parameters, callback) {
        var projectCode = $("#project").val();
        var teamCode = $("#Team").val();
        var startDate = parameters.startStr.replace("T00:00:00Z","");
        var endDate = parameters.endStr.replace("T00:00:00Z", "");
        var Jsondata = {};
        Jsondata.SearchItem = [];
        Jsondata.EntityName = "3l6xvhhvcxp";
        Jsondata.index = 0;
        Jsondata.size = 100;
        Jsondata.SearchItem.push({ "Name": "IsDeleted", "Value": 0, "Operator": 'Equal', 'Method': 'AND' });

        if (IsNotNull(projectCode)) {
            Jsondata.SearchItem.push({ "Name": "ProjectCode", "Value": projectCode, "Operator": 'Equal', 'Method': 'AND' });
        };

        if (IsNotNull(teamCode)) {
            var tm = GetTeamStaff();
            alert(tm);
            var staffList = [];
            $.each(tm, function (i, o) {
                staffList.push(o.id);
            });
            if (staffList.length > 0) {
                Jsondata.SearchItem.push({ "Name": "Person", "Value": staffList.join("|C4|"), "Operator": 'In', 'Method': 'AND' });
            }
        };

        if (IsNotNull(startDate) && IsNotNull(endDate)) {           
            var compareValue = moment(startDate).valueOf() + "|C4|" + moment(endDate).valueOf();
            
            Jsondata.SearchItem.push({
                "Method": "AND",
                "Name": "",
                "Operator": "",
                "SubSearchItems": [{
                    "Method": "OR",
                    "Name": "StartDate",
                    "Operator": "Range",
                    "SubSearchItems": null,
                    "Value": compareValue
                },
                {
                    "Method": "OR",
                    "Name": "EndDate",
                    "Operator": "Range",
                    "SubSearchItems": null,
                    "Value": compareValue
                }]
            });
        };

        Jsondata.Columns = ["_id", "Project", "ProjectCode", "Metadata-Person_relationsvalue", "Person", "Task", "StartDate", "EndDate"];
        console.log("GetEvents-parameters", Jsondata);
        var result = [];
        $.ajax({
            url: requrl,
            type: 'post',
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(Jsondata),
            dataType: 'json',
            success: function (response) {
                if (response.StatusCode === 200) {
                    if (response.Data.total > 0) {
                        $.each(response.Data.rows, function (i, o) {
                            result.push({
                                id:o._id,
                                resourceId: o.Person[0],
                                title: IsNotNull(projectCode) ? o.Task : o.Project,
                                start: moment(o.StartDate).format("YYYY-MM-DD"),
                                end: moment(o.EndDate).add(1, "day").format("YYYY-MM-DD"),
                                staffName:o["Metadata-Person_relationsvalue"][0].StaffName
                            });
                        });
                    }
                }
                console.log("GetEvents-results", result);
                callback(result);
            }
        });

    };

    function IsNotNull(value) {
        return value !== "" && value !== null && value !== undefined ? true : false;
    };

   

    function GetUserIcon(staffname) {
        var imgUrl = IconUrl;
        for (i = 0; i < ResourceList.length; i++) {
            var o = ResourceList[i];
            if (o.title == staffname) return imgUrl.replace("{{StaffCode}}", o.id);
        }
        return "";
    };

    function LoadCalendar() {
        var calendarEl = document.getElementById('calendar');
        calendar = new FullCalendar.Calendar(calendarEl, {
            plugins: ['interaction', 'resourceTimeline'],
            timeZone: 'UTC',
            header: {
                left: 'today prev,next',
                center: 'title',
                right: 'resourceTimelineMonth,resourceTimeline3Month,resourceTimeline6Month'
            },
            defaultView: 'resourceTimelineMonth',
            scrollTime: '08:00',
            aspectRatio: 1.5,
            eventLimit: true,
            navLinks: true,
            views: {
                resourceTimeline3Month: {
                    type: 'resourceTimelineMonth',
                    duration: { months: 3 },
                    buttonText: '3 month'
                },
                resourceTimeline6Month: {
                    type: 'resourceTimelineMonth',
                    duration: { months: 6 },
                    buttonText: 'harf year'
                }
            },

            editable: false,
            resourceLabelText: 'Staff',

            resources: function (parameter, callback) {
                console.log("resources--parameter", parameter);

                GetResources(callback);

                setTimeout(function () {
                    $(".fc-widget-content").find(".fc-cell-text").each(function (index, item) {
                        var htm = $(this).html();
                        if (htm.indexOf("<img style=") >= 0) return;
                        var text = $(this).text();
                        var imgUrl = GetUserIcon(text);                       
                        $(this).prepend("<img style='width:30px;height:30px;border-radius: 3px;' src='" + imgUrl + "'/><br>");
                    });
                }, 500);
            },
            events: function (parameter, callback) {
                console.log("events-parameter:", parameter);
                setTimeout(function () {
                    $(".fc-license-message").hide();
                    $(".fc-timeline-event").attr("target", "_blank");
                }, 500);
                GetEvents(parameter, callback);
            },
            eventClick: function (obj) {
                console.log(obj.event);
                console.log(obj.event.title);
            },
            eventMouseover: function (event, jsEvent, view) {
                console.log(event);
            },
            eventMouseout: function (event, jsEvent, view) { 
                console.log(event);
            }
        });
        calendar.render();


        $(".fc-resourceTimelineMonth-button,.fc-resourceTimeline3Month-button,.fc-resourceTimeline6Month-button,.fc-resourceTimelineYear-button").on('click', function () {
            setTimeout(function () {
                $(".fc-timeline-event").attr("target", "_blank");
                $(".fc-widget-content").find(".fc-cell-text").each(function (index, item) {
                    var htm = $(this).html();                   
                    if (htm.indexOf("<img style=") >= 0) return;
                    var text = $(this).text();
                    var imgUrl = GetUserIcon(text);
                    $(this).prepend("<img style='width:30px;height:30px;border-radius: 3px;' src='" + imgUrl + "'/><br>");
                });
            }, 500);
        });
        $(".fc-prev-button,.fc-next-button").on("click", function () {
            $(".fc-timeline-event").attr("target", "_blank");
        });

    };

    $(function () {
        GetProjectList();
        GetTeams();
    });
</script>

